<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" :rows="2" labelWidth="100" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      ref="table"
      columnsRef="jcqrTable"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      selectionType="single"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="columns => (this.selectColumns = columns)"
    >
      <template slot="controls">
        <!-- <el-button size="small" type="primary" @click="confirm">交车</el-button> -->
        <multiuse-button size="small" type="primary" :click="confirm" :auth-list="auths" auth-mark="/repair/repairReception/giveCar/delivery">交车</multiuse-button>

        <!-- <AjaxButton size="small" type="primary" :click="cancel">取消交车</AjaxButton> -->
        <multiuse-button size="small" type="primary" :click="cancel" :auth-list="auths" auth-mark="/repair/repairReception/giveCar/Canceldelivery">取消交车</multiuse-button>

        <el-button size="small" type="primary" @click="giveCarExport">导出</el-button>
        <el-button size="small" type="primary" @click="printCard">打印出门证</el-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <confirmModal :type="handleType" :rowData="selectColumns[0]" @close="closeHandler" />
    </BaseDialog>
    <div v-if="printVehicledShow">
      <BasePrint ref="printVehicled" :data="this.printList" template="templateGiveCar" />
    </div>
  </div>
</template>

<script>
import { searchGiveCar, cancel, getUserListSelect, getAllUser, giveCarInfoExport } from '@/api/repair/repairReception/giveCar';
import { dictionary } from '@/utils/dictMixin';
import confirmModal from './confirmModal';
import { authority } from '@/utils/authMixin';
import { unLockerUser, lockUser } from '@/api/repair/repairReception/customer';
import { exportExcelFile } from '@/utils/index';

import { getUserId } from '@/assets/js/auth';
import { getBrand, getSeries, getModel, getRegion } from '@/api/customerRepair/customerCare/insuranceDueRemind/index';
import moment from 'moment';
export default {
  name: 'giveCar',
  components: {
    confirmModal
  },
  mixins: [dictionary, authority],
  data() {
    return {
      printVehicledShow: false,
      topFilterList: this.createTopFilters(),
      fetchParams: {},
      selectColumns: [],
      visible: false,
      dialogTitle: '',
      fetchApi: searchGiveCar,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      conf: { confirm: '' },
      printList: {},
      modelList: [],
      userId: '',
      serviceAdvisorData: []
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.initSelect();
    this.queryModel();
    this.serachService();
    this.getUserId();
  },
  created() { },
  methods: {
    async initSelect() {
      const resUser = await getAllUser();
      if (resUser != null) {
        this.columns.find(x => x.dataIndex === 'DELIVERY_USER').editItems = resUser.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
        this.columns.find(x => x.dataIndex === 'BALANCE_HANDLER').editItems = resUser.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
        // if (this.columns.find(x => x.dataIndex === 'LOCK_USER') != null) {
        //   this.columns.find(x => x.dataIndex === 'LOCK_USER').editItems = resUser.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
        // }
      }
      // 服务顾问
      let serviceAdvisorList = await getUserListSelect();
      if (serviceAdvisorList != null) {
        this.topFilterList.find(item => item.fieldName === 'serviceAdvisor').itemList = serviceAdvisorList.data.map(x => ({ value: x.userId, text: x.employeeName }));
        this.columns.find(x => x.dataIndex === 'SERVICE_ADVISOR').editItems = serviceAdvisorList.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      }
    },
    createTopFilters() {
      return [
        {
          type: 'SELECT',
          label: '交车标识',
          fieldName: 'deliveryTag',
          placeholder: '请输入',
          itemList: this.createDictList('8001')
        },
        {
          type: 'INPUT',
          label: '工单编号',
          fieldName: 'roNo',
          placeholder: '请输入'
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'serviceAdvisor',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          placeholder: '请输入'
        },
        {
          type: 'RANGE_DATE',
          label: '结算时间',
          fieldName: 'balanceTimeBegin|balanceTimeEnd',
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'RANGE_DATE',
          label: '结清时间',
          fieldName: 'squareDateBegin|squareDateEnd',
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'RANGE_DATE',
          label: '关单时间',
          fieldName: 'balanceCloseTimeBegin|balanceCloseTimeEnd',
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'RANGE_DATE',
          label: '提交结算时间',
          fieldName: 'forBalanceTimeBegin|forBalanceTimeEnd',
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '请输入'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '交车标识',
          dataIndex: 'DELIVERY_TAG',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8001'),
          render: props => {
            return <span>{this.createDictText(props.row.DELIVERY_TAG, '8001')}</span>;
          }
        },
        {
          title: '交车日期',
          dataIndex: 'DELIVERY_DATE',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          showOverflowTooltip: true
        },
        {
          title: '交车人',
          dataIndex: 'DELIVERY_USER',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input'
        },
        {
          title: '是否结清',
          dataIndex: 'PAY_OFF',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.PAY_OFF, '1004')}</span>;
          }
        },
        {
          title: '工单号',
          dataIndex: 'RO_NO',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: '110'
        },
        {
          title: '开单日期',
          dataIndex: 'RO_CREATE_DATE',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          showOverflowTooltip: true
        },
        {
          title: '车牌号',
          dataIndex: 'LICENSE',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: 'VIN',
          dataIndex: 'VIN',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: '150'
        },
        {
          title: '服务顾问',
          dataIndex: 'SERVICE_ADVISOR',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input'
        },
        {
          title: '车主',
          dataIndex: 'OWNER_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送修人',
          dataIndex: 'DELIVERER',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送修人电话',
          dataIndex: 'DELIVERER_PHONE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送修人手机',
          dataIndex: 'DELIVERER_MOBILE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '结算时间',
          dataIndex: 'BALANCE_TIME',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          showOverflowTooltip: true
        },
        {
          title: '结算单号',
          dataIndex: 'BALANCE_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '结算员',
          dataIndex: 'BALANCE_HANDLER',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input'
        },
        {
          title: '工单拆分状态',
          dataIndex: 'RO_SPLIT_STATUS',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8002'),
          render: props => {
            return <span>{this.createDictText(props.row.RO_SPLIT_STATUS, '8002')}</span>;
          }
        },
        {
          title: '锁定人',
          dataIndex: 'LOCK_USER ',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.getUserName(props.row.LOCK_USER)}</span>;
          }
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '实收金额',
          dataIndex: 'RECEIVE_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          hidden: true
        },
        {
          title: '维修类型',
          dataIndex: 'REPAIR_TYPE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          hidden: true
        },
        {
          title: '车型',
          dataIndex: 'MODEL_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          hidden: true,
          width: 120,
          render: props => {
            return <span>{this.getModelName(props.row.MODEL)}</span>;
          }
        },
        {
          title: '提交结算时间',
          dataIndex: 'FOR_BALANCE_TIME',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          showOverflowTooltip: true
        },
        {
          title: '回访时间',
          dataIndex: 'TRACE_TIME',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8029'),
          render: props => {
            return <span>{this.createDictText(props.row.TRACE_TIME, '8029')}</span>;
          }
        },
        {
          title: '是否回访',
          dataIndex: 'IS_TRACE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.IS_TRACE, '1004')}</span>;
          }
        }
      ];
    },
    // 获取当前用户
    async getUserId() {
      console.log('获取当前用户');
      this.userId = await getUserId();
    },
    async confirm() {
      if (this.selectColumns.length == 0) {
        return this.$notify.error({ title: '提示信息', message: '请选择记录!' });
      }
      let deliveryTag = this.selectColumns[0].DELIVERY_TAG;
      if (deliveryTag != '80011002') {
        return this.$notify.error({ title: '提示信息', message: '请选择未交车的数据!' });
      }
      console.log(this.selectColumns[0].LOCK_USER, this.userId, '-------')
      if (this.selectColumns[0].LOCK_USER !== null && this.selectColumns[0].LOCK_USER != this.userId) {
        return this.$notify.warning({ title: '提示信息', message: `此单号[${this.selectColumns[0].RO_NO}]已被用户[${this.getUserName(this.selectColumns[0].LOCK_USER)}]锁定!` });
      }
      let objGo = {
        tabName: 'TT_BALANCE_ACCOUNTS',
        field: 'BALANCE_NO',
        val: this.selectColumns[0].BALANCE_NO
      };
      let res1 = await lockUser(objGo);
      this.handleType = 'confirm';
      this.showHandler();
    },
    printCard() {
      this.printVehicledShow = true;
      if (this.selectColumns.length == 0) {
        return this.$notify.error({ title: '提示信息', message: '请选择记录!' });
      } else if (this.selectColumns[0].DELIVERY_TAG == 80011002) {
        return this.$notify.error({ title: '提示信息', message: '请选择已交车的数据!' });
      } else {
        let balanceTime = moment(this.selectColumns[0].BALANCE_TIME).format('YYYY-MM-DD');
        let roCreateDate = moment(this.selectColumns[0].RO_CREATE_DATE).format('YYYY-MM-DD');
        let balanceHandler = this.selectColumns[0].BALANCE_HANDLER;
        let users = this.columns.find(x => x.dataIndex === 'BALANCE_HANDLER').editItems;
        users.forEach(x => {
          if (x.value === balanceHandler) {
            balanceHandler = x.text;
          }
        });
        this.printList = {
          license: this.selectColumns[0].LICENSE,
          ownerName: this.selectColumns[0].OWNER_NAME,
          vin: this.selectColumns[0].VIN,
          modelName: this.getModelName(this.selectColumns[0].MODEL),
          balanceHandler: balanceHandler,
          balanceTime: balanceTime,
          roCreateDate: roCreateDate,
          receiveAmount: this.selectColumns[0].RECEIVE_AMOUNT.toFixed(2),
          repairTypeName: this.selectColumns[0].REPAIR_TYPE_NAME,
          remark: this.selectColumns[0].REMARK
        };
        this.$nextTick(() => {
          this.$refs.printVehicled.EXCUTE_PRINT();
        });
      }
    },
    showHandler() {
      this.dialogTitle = `提示:${this.conf[this.handleType]}`;
      this.visible = true;
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // 查询所有车型(供table使用)
    async queryModel() {
      const res = await getModel();
      this.modelList = res.data.map(x => ({ text: x.MODEL_NAME, value: x.MODEL_ID + '' }));
    },
    getModelName(MODEL_ID) {
      const item = this.modelList.find(x => {
        return x.value == MODEL_ID;
      });
      return item ? item.text : '';
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    async cancel() {
      if (this.selectColumns.length == 0) {
        return this.$notify.error({ title: '提示信息', message: '请选择记录!' });
      }
      let roNo = this.selectColumns[0].RO_NO;
      let deliveryTag = this.selectColumns[0].DELIVERY_TAG;
      if (deliveryTag != '80011001') {
        return this.$notify.error({ title: '提示信息', message: '请选择已交车的数据!' });
      }
      let flag = false;
      const res = await cancel(roNo, {});
      if (res.resultCode == 200) {
        flag = true;
        this.$notify.success({ title: '提示信息', message: '取消交车成功!' });
      } else {
        this.$notify.error({ title: '提示信息', message: '取消交车失败!' });
      }
      // 取消锁定人
      if (flag) {
        let objGo = {
          tabName: 'TT_BALANCE_ACCOUNTS',
          field: 'BALANCE_NO',
          val: this.selectColumns[0].BALANCE_NO
        };
        let res1 = await unLockerUser(objGo);
      }
      // 重新加载
      this.fetchParams = { ...this.fetchParams };
    },
    getUserName(userId) {
      const item = this.serviceAdvisorData.find(x => {
        return x.value == userId;
      });
      return item ? item.text : '';
    },
    // 导出
    giveCarExport() {
      giveCarInfoExport(this.fetchParams).then(res => {
        exportExcelFile(res, '交车确认');
      });
    },
    async serachService() {
      let res = await getAllUser();
      this.serviceAdvisorData = res.data.map(x => ({ text: x.employeeName, value: x.userId }));
    }
  }
};
</script>

<style lang="less" scoped></style>
